package com.cango.student.algorithm.nodepackage;

/**
 * 删除倒数第n个元素
 */
public class DeleteFoot {


    public static Node deleteFoot(Node node, int num) {
        Node tmp = node;
        // 从0开始，先指定标的节点
        for (int i = 0; i < num; i++) {
            tmp = tmp.next;
        }
        Node pre = node;
        Node cur = node;
        while (tmp != null) {
            tmp = tmp.next;
            pre = cur;
            cur = cur.next;
        }

        pre.next = cur.next;

        return node;
    }

    public static void main(String[] args) {
        Node linkNode1 = new Node();
        linkNode1.data = 1;
        Node linkNode2 = new Node();
        linkNode2.data = 2;
        Node linkNode3 = new Node();
        linkNode3.data = 3;
        Node linkNode4 = new Node();
        linkNode4.data = 4;
        Node linkNode5 = new Node();
        linkNode5.data = 5;
        Node linkNode6 = new Node();
        linkNode6.data = 6;

        linkNode1.next = linkNode2;
        linkNode2.next = linkNode3;
        linkNode3.next = linkNode4;
        linkNode4.next = linkNode5;
        linkNode5.next = linkNode6;


        Node node = deleteFoot(linkNode1, 5);
        while (node != null) {
            System.out.println(node.data);
            node = node.next;
        }

    }
}
